package com.heima.item.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.item.pojo.Item;
import com.heima.item.pojo.ItemStock;
import com.heima.item.service.IItemService;
import com.heima.item.service.IItemStockService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class RedisHandler implements InitializingBean {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IItemService itemService;

    @Resource
    private IItemStockService itemStockService;

    private static final ObjectMapper MAPPER=new ObjectMapper();

    @Override
    public void afterPropertiesSet() throws Exception {
        //1. 查询商品信息
        List<Item> itemList = itemService.list();

        //2. 将商品信息放入redis
        for (Item item : itemList) {
            //item序列化
            String itemJson = MAPPER.writeValueAsString(item);

            //存储
            stringRedisTemplate.opsForValue().set("item:id:"+item.getId(),itemJson);
        }

        //3. 查询商品库存信息
        List<ItemStock> itemStockList = itemStockService.list();

        //4. 将商品库存放入redis
        for (ItemStock itemStock : itemStockList) {
            //序列化
            String itemStockJson = MAPPER.writeValueAsString(itemStock);

            //存储
            stringRedisTemplate.opsForValue().set("item:stock:id:"+itemStock.getId(),itemStockJson);
        }
    }

    public void saveItem(Item item){
        try {
            //item序列化
            String itemJson = null;
            itemJson = MAPPER.writeValueAsString(item);
            //存储
            stringRedisTemplate.opsForValue().set("item:id:"+item.getId(),itemJson);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }

    public void removeItem(Long id){
        stringRedisTemplate.delete("item:id:"+id);
    }
}
